package com.leyou.cart.listener;

import com.leyou.common.constants.LyConstants;
import com.leyou.common.constants.MQConstants;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class CartListener {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.Queue.CART_UP, durable = "true"),
            exchange = @Exchange(value = MQConstants.Exchange.CART_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKey.cart_UP_KEY
    ))
    public void cartUp(Long userId) {
        //接收到下单通知获取购物车
        String key = LyConstants.CART_PRE+ userId;
        BoundHashOperations<String, String, String> cartMap = redisTemplate.boundHashOps(key);
        //转移购物车
        redisTemplate.opsForHash().putAll(key+"UP",cartMap.entries());
        //清空购物车
        redisTemplate.delete(key);
    }

    /**
     * 取消订单
     * @param userId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MQConstants.Queue.CART_DOWN, durable = "true"),
            exchange = @Exchange(value = MQConstants.Exchange.CART_EXCHANGE_NAME, type = ExchangeTypes.TOPIC),
            key = MQConstants.RoutingKey.cart_DOWN_KEY
    ))
    public void cartW(Long userId) {
        //接收到下单通知获取购物车
        String key = LyConstants.CART_PRE+ userId;
        BoundHashOperations<String, String, String> cartMap = redisTemplate.boundHashOps(key+"UP");
        //转移购物车
        redisTemplate.opsForHash().putAll(key,cartMap.entries());
        redisTemplate.delete(key+"UP");
    }

}